package com.laundry.service;

import com.laundry.entity.Merchant;
import com.laundry.entity.Service;
import com.laundry.repository.MerchantRepository;
import com.laundry.repository.ServiceRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class SearchService {
    
    private final ServiceRepository serviceRepository;
    private final MerchantRepository merchantRepository;
    
    public Map<String, Object> searchAll(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("orderCount").descending());
        
        // 搜索服务
        Page<Service> services = serviceRepository.findByStatusAndNameContaining(
                Service.ServiceStatus.ACTIVE, keyword, pageable);
        
        // 搜索商家
        Page<Merchant> merchants = merchantRepository.findByStatusAndNameContaining(
                Merchant.MerchantStatus.ACTIVE, keyword, pageable);
        
        Map<String, Object> result = new HashMap<>();
        result.put("services", services);
        result.put("merchants", merchants);
        result.put("keyword", keyword);
        result.put("totalResults", services.getTotalElements() + merchants.getTotalElements());
        
        return result;
    }
    
    public Page<Service> searchServices(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("orderCount").descending());
        return serviceRepository.findByStatusAndNameContaining(
                Service.ServiceStatus.ACTIVE, keyword, pageable);
    }
    
    public Page<Merchant> searchMerchants(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("rating").descending());
        return merchantRepository.findByStatusAndNameContaining(
                Merchant.MerchantStatus.ACTIVE, keyword, pageable);
    }
    
    public Map<String, Object> getRecommendations() {
        Pageable pageable = PageRequest.of(0, 10);
        
        Map<String, Object> result = new HashMap<>();
        result.put("recommendedServices", serviceRepository.findRecommendedServices(pageable));
        result.put("hotServices", serviceRepository.findHotServices(pageable));
        result.put("topRatedMerchants", merchantRepository.findTopRatedMerchants(pageable));
        result.put("popularMerchants", merchantRepository.findPopularMerchants(pageable));
        
        return result;
    }
}
